<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Viewer</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container { max-width: 1200px; margin-top: 2rem; }
        #dataDisplay { margin-top: 1rem; }
        .json-viewer { max-height: 600px; overflow-y: auto; }
        pre { 
            background-color: #f8f9fa; 
            padding: 1rem; 
            border-radius: 0.25rem;
            white-space: pre-wrap;       /* CSS 3 */
            white-space: -moz-pre-wrap;  /* Mozilla */
            white-space: -pre-wrap;      /* Opera 4-6 */
            white-space: -o-pre-wrap;    /* Opera 7 */
            word-wrap: break-word;       /* Internet Explorer 5.5+ */
        }
        pre.nowrap { 
            white-space: pre !important;
            overflow-x: auto;
            word-wrap: normal !important;
        }
        #filterContainer { margin-top: 1rem; }
        .filter-row { margin-bottom: 0.5rem; }
        .filter-remove { cursor: pointer; }
    </style>
</head>
<body>
    <div class="container">
        <h2>Data Viewer</h2>
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    <label for="fileSelect">Select File:</label>
                    <select class="form-control" id="fileSelect"></select>
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <label for="startIdx">Start Index:</label>
                    <input type="number" class="form-control" id="startIdx" value="0" min="0">
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <label for="count">Number of Items:</label>
                    <input type="number" class="form-control" id="count" value="10" min="1">
                </div>
            </div>
        </div>

        <div id="filterContainer">
            <h4>Filters</h4>
            <div id="filterRows"></div>
            <button class="btn btn-secondary btn-sm mt-2" onclick="addFilterRow()">Add Filter</button>
        </div>

        <div class="row mt-3">
            <div class="col">
                <button class="btn btn-primary" onclick="loadData()">Load Data</button>
                <button class="btn btn-secondary" id="wrapButton" onclick="toggleWordWrap()">Disable Word Wrap</button>
            </div>
        </div>
        <div id="dataDisplay" class="json-viewer">
            <pre id="jsonContent"></pre>
        </div>
    </div>

    <script>
        let currentFile = '';
        let availableFields = new Set();
        let wordWrapEnabled = true;
        
        // Load available files on page load
        window.onload = async function() {
            await updateFileList();
            // Load first file's data by default
            const fileSelect = document.getElementById('fileSelect');
            if (fileSelect.options.length > 0) {
                currentFile = fileSelect.options[0].value;
                loadData();
            }
        };

        // Update file list (only called once at startup)
        async function updateFileList() {
            const response = await fetch('/files');
            const files = await response.json();
            const fileSelect = document.getElementById('fileSelect');
            fileSelect.innerHTML = '';
            files.forEach(file => {
                const option = document.createElement('option');
                option.value = file;
                option.textContent = file;
                fileSelect.appendChild(option);
            });

            // Add change event listener to update available fields when file changes
            fileSelect.addEventListener('change', function() {
                loadData();
            });
        }

        function addFilterRow() {
            const filterRows = document.getElementById('filterRows');
            const row = document.createElement('div');
            row.className = 'filter-row d-flex gap-2';
            
            const fieldInput = document.createElement('input');
            fieldInput.className = 'form-control';
            fieldInput.placeholder = 'Field';
            fieldInput.setAttribute('list', 'availableFields');
            
            const valueInput = document.createElement('input');
            valueInput.className = 'form-control';
            valueInput.placeholder = 'Value';
            
            const removeBtn = document.createElement('span');
            removeBtn.className = 'filter-remove btn btn-danger btn-sm';
            removeBtn.textContent = '×';
            removeBtn.onclick = () => row.remove();
            
            row.appendChild(fieldInput);
            row.appendChild(valueInput);
            row.appendChild(removeBtn);
            filterRows.appendChild(row);
        }

        function getFilters() {
            const filters = [];
            document.querySelectorAll('.filter-row').forEach(row => {
                const field = row.querySelector('input:first-child').value;
                const value = row.querySelector('input:nth-child(2)').value;
                if (field && value) {
                    filters.push({ field, value });
                }
            });
            return filters;
        }

        function updateAvailableFields(data) {
            availableFields.clear();
            data.forEach(item => {
                Object.keys(item).forEach(key => availableFields.add(key));
            });

            // Update datalist for field inputs
            let datalist = document.getElementById('availableFields');
            if (!datalist) {
                datalist = document.createElement('datalist');
                datalist.id = 'availableFields';
                document.body.appendChild(datalist);
            }
            datalist.innerHTML = '';
            availableFields.forEach(field => {
                const option = document.createElement('option');
                option.value = field;
                datalist.appendChild(option);
            });
        }

        // Toggle word wrap
        function toggleWordWrap() {
            const pre = document.getElementById('jsonContent');
            const button = document.getElementById('wrapButton');
            wordWrapEnabled = !wordWrapEnabled;
            if (wordWrapEnabled) {
                pre.classList.remove('nowrap');
                button.textContent = 'Disable Word Wrap';
            } else {
                pre.classList.add('nowrap');
                button.textContent = 'Enable Word Wrap';
            }
        }

        // Load and filter data based on current selection
        async function loadData() {
            const fileSelect = document.getElementById('fileSelect');
            const startIdx = document.getElementById('startIdx').value;
            const count = document.getElementById('count').value;
            const file = fileSelect.value;
            const filters = getFilters();

            if (!file) return;

            try {
                const response = await fetch(`/data?file=${encodeURIComponent(file)}&start=${startIdx}&count=${count}`);
                let data = await response.json();

                // Apply filters
                filters.forEach(filter => {
                    data = data.filter(item => {
                        const itemValue = String(item[filter.field] || '');
                        const filterValue = String(filter.value);
                        return itemValue.includes(filterValue);
                    });
                });

                // Update available fields for the current data
                updateAvailableFields(data);

                // Display filtered data
                document.getElementById('jsonContent').textContent = JSON.stringify(data, null, 2);
            } catch (error) {
                console.error('Error loading data:', error);
                document.getElementById('jsonContent').textContent = 'Error loading data';
            }
        }
    </script>
</body>
</html>
